package com.jiada.shiro.test.security;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;

import com.jiada.shiro.test.model.Permission;
import com.jiada.shiro.test.model.User;
import com.jiada.shiro.test.model.UserExample;
import com.jiada.shiro.test.service.UserService;

@Service
public class systemAuthorizingRealm extends AuthorizingRealm{

	@Resource
	UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String loginName = (String) getAvailablePrincipal(principals);
		User user = userService.selectByUserName(loginName);
		if(user !=null){
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			info.addStringPermission("user");
	        List<Permission> permissionList = userService.getUserPermissions(user);
	        for(Permission permission : permissionList){
	        	String str = permission.getPer_type();
	        	if (str == null || "".equals(str)) {
	        		
				}else{
					info.addStringPermission(str);
				}
	        	
	        }
		return info;
		}else{
			return null;
		}
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String account = String.valueOf(token.getPrincipal());
        String password = new String((char[]) token.getCredentials());
        // 通过数据库进行验证
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(account).andPasswordEqualTo(password);
        final User authentication = userService.selectByExample(example).get(0);
        if (authentication == null) {
            throw new AuthenticationException("用户名或密码错误.");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(account, password, getName());
        return authenticationInfo;
	}

}
